//
//  HZMHomePageViewController.m
//  糖糖大魔王
//
//  Created by 韩震明 on 15/10/22.
//  Copyright © 2015年 韩震明. All rights reserved.
//

#import "HZMHomePageViewController.h"
#import "HZMBannerDetailsVC.h"
#import "HZMSubject_DetailsViewController.h"
#import "HZMTableDetailsVC.h"
#import "HZMTableDetailsType1VC.h"
#import "HZMOtherViewController.h"




@interface HZMHomePageViewController ()<UITableViewDataSource,UITableViewDelegate,UICollectionViewDataSource,UICollectionViewDelegate,UIScrollViewDelegate,UIGestureRecognizerDelegate>

@property (nonatomic, retain) UITableView *tableView;
@property (nonatomic, retain) UIScrollView *scroll;
@property (nonatomic, retain) MBProgressHUD *hud;
@property (nonatomic, retain) UICollectionView *collection;
/*! scrollView数据 */
@property (nonatomic, retain) NSMutableArray *banner;
/*! collectionView数据 */
@property (nonatomic, retain) NSMutableArray *entry_list;
/*! tableView数据 */
@property (nonatomic, retain) NSMutableArray *topic;
@property (nonatomic, assign) NSInteger page;
@property (nonatomic, retain) UIView *backOfSCView;
@property (nonatomic, assign) CGFloat oldOffset;

@end

@implementation HZMHomePageViewController

- (void)dealloc
{
    [_tableView release];
    [_scroll release];
    [_hud release];
    [_collection release];
    [_banner release];
    [_entry_list release];
    [_topic release];
    [_backOfSCView release];
    [super dealloc];
}

//- (UIStatusBarStyle)preferredStatusBarStyle
//{
//    return UIStatusBarStyleLightContent;
//}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
//    [self createNetWork];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
    UIView *status = [[UIView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, 20)];
    [self.navigationController.view addSubview:status];
    [status release];
    status.backgroundColor = [UIColor redColor];
    [self setNeedsStatusBarAppearanceUpdate];
}



- (BOOL)prefersStatusBarHidden
{
    return NO;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationController.hidesBarsOnSwipe = YES;

    
    [self createTableView];
    
    [self createScrollView];
    
    [self createCollectionView];
    
    [self createData];
    
    self.hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    self.hud.labelText = @"正在加载...";
    
    [self createNetWork];
    
    [self refresh];
    
}



#pragma mark - MJRefresh Method
- (void)refresh
{
    self.tableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        self.page = 0;
        [self createData];
        
    }];
    
    self.tableView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        self.page++;
        [self createData];
        
    }];
}



#pragma mark TableView Setting
- (void)createTableView
{
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT - 48) style:UITableViewStylePlain];
    self.tableView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:self.tableView];
    [_tableView release];
    
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    
    self.tableView.rowHeight = 150;
    self.tableView.separatorStyle = NO;
    self.tableView.showsVerticalScrollIndicator = NO;
//    self.tableView.tag = 10000;
    
    self.backOfSCView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 320)];
    self.backOfSCView.backgroundColor = [UIColor whiteColor];
    self.tableView.tableHeaderView = self.backOfSCView;
//    self.tableView.contentInset = UIEdgeInsetsMake(320, 0, 0, 0);
    [self.backOfSCView release];
}



#pragma mark - TableView Delegate Method
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.topic.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *reuse = @"reuse";
    HZMTopicTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuse];
    if (!cell) {
        cell = [[[HZMTopicTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuse] autorelease];
    }
    [cell.picImageView sd_setImageWithURL:[NSURL URLWithString:[self.topic[indexPath.row] pic]] placeholderImage:[UIImage imageNamed:@"back.gif"]];
    cell.titleLabel.text = [self.topic[indexPath.row] title];
    cell.likeImageView.image = [UIImage imageNamed:@"like.png"];
    cell.likeLabel.text = [self.topic[indexPath.row] likes];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([[self.topic[indexPath.row] cellType] isEqualToString:@"0"]) {
        HZMTableDetailsVC *tableVC = [[HZMTableDetailsVC alloc] init];
        tableVC.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:tableVC animated:YES];
        tableVC.urlStr = [NSString stringWithFormat:@"http://open3.bantangapp.com/topic/info?app_installtime=1445332782.662591&app_versions=4.2.3&channel_name=appStore&client_id=bt_app_ios&client_secret=9c1e6634ce1c5098e056628cd66a17a5&id=%@&oauth_token=bf8be334eb1fd06b1bf65f5883dd415a&os_versions=9.1&screensize=1242&statistics_uv=1&track_device_info=iPhone72C1&track_deviceid=2F83AC09-B470-4C43-9DEE-E0FB95B4B438&track_user_id=1457891&v=7", [self.topic[indexPath.row] cellId]];
        tableVC.topicModel = self.topic[indexPath.row];
    } else {
        HZMTableDetailsType1VC *type = [[HZMTableDetailsType1VC alloc] init];
        type.strUrl = [NSString stringWithFormat:@"http://open3.bantangapp.com/topic/info?app_installtime=1445332782.662591&app_versions=4.2.3&channel_name=appStore&client_id=bt_app_ios&client_secret=9c1e6634ce1c5098e056628cd66a17a5&id=%@&oauth_token=bf8be334eb1fd06b1bf65f5883dd415a&os_versions=9.1&screensize=1242&statistics_uv=1&track_device_info=iPhone72C1&track_deviceid=2F83AC09-B470-4C43-9DEE-E0FB95B4B438&track_user_id=1457891&v=7", [self.topic[indexPath.row] cellId]];
        type.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:type animated:YES];
    }
}



#pragma mark ScrollView Setting
/*! 轮播图 */
- (void)createScrollView
{
    self.scroll = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, 200)];
    self.scroll.backgroundColor = [UIColor whiteColor];
    [self.backOfSCView addSubview:self.scroll];
    [_scroll release];
    
    self.scroll.pagingEnabled = YES;
    self.scroll.bounces = NO;
    self.scroll.showsHorizontalScrollIndicator = NO;
    
    [NSTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector(setOffSet) userInfo:nil repeats:YES];
}

#pragma mark Timer Selector Method
- (void)setOffSet
{
    static NSInteger i = 1;
    self.scroll.contentOffset = CGPointMake(WIDTH * i, 0);
    if (i > self.banner.count) {
        i = 0;
    }
    i++;
}



#pragma mark ScrollViewData
- (void)reloadScrollViewData
{
    
    self.scroll.contentSize = CGSizeMake((self.banner.count + 2) * WIDTH, 0);
    
    UIImageView *firstImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, 200)];
    [firstImageView sd_setImageWithURL:[NSURL URLWithString:[self.banner[self.banner.count - 1] photo]]placeholderImage:[UIImage imageNamed:@"back.gif"]];
    [self.scroll addSubview:firstImageView];
    [firstImageView release];
    firstImageView.userInteractionEnabled = YES;
    firstImageView.tag = 1001;

    for (NSInteger i = 1; i <self.banner.count + 1 ; i++) {
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(i * WIDTH, 0, WIDTH, 200)];
        [imageView sd_setImageWithURL:[NSURL URLWithString:[self.banner[i - 1] photo]] placeholderImage:[UIImage imageNamed:@"back.gif"]];
        [self.scroll addSubview:imageView];
        [imageView release];
        imageView.userInteractionEnabled = YES;
        imageView.tag = 1001 + i;
        
        UITapGestureRecognizer * singleFinger = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(click:)];
        singleFinger.delegate = self;
        [imageView addGestureRecognizer:singleFinger];
        // 观察内存情况
        [singleFinger release];
    }
    
    UIImageView *lastImageView = [[UIImageView alloc] initWithFrame:CGRectMake((self.banner.count + 1) * WIDTH, 0, WIDTH, 200)];
    [lastImageView sd_setImageWithURL:[NSURL URLWithString:[self.banner[0] photo]] placeholderImage:[UIImage imageNamed:@"back.gif"]];
    [self.scroll addSubview:lastImageView];
    [lastImageView release];
    lastImageView.userInteractionEnabled = YES;
    lastImageView.tag = self.banner.count + 2;
    
    self.scroll.contentOffset = CGPointMake(WIDTH, 0);
    
    self.scroll.delegate = self;
}

#pragma mark Tap Click Method
- (void)click:(UITapGestureRecognizer *)singleFinger
{
    UIImageView *tapView = (UIImageView *)[self.scroll viewWithTag:singleFinger.view.tag];
        if ([[self.banner[tapView.tag - 1002] bannerType] isEqualToString:@"topic_list"]) {
            HZMBannerDetailsVC *bannerDetailsVC = [[HZMBannerDetailsVC alloc] init];
            bannerDetailsVC.bannerModel = self.banner[tapView.tag - 1002];
            bannerDetailsVC.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:bannerDetailsVC animated:YES];
            [bannerDetailsVC release];
        } else {
            HZMBaseWebView *webView = [[HZMBaseWebView alloc] init];
            webView.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:webView animated:YES];
            webView.WebViewStrUrl = [self.banner[tapView.tag - 1002] extend];
            webView.titleForWeb = [self.banner[tapView.tag - 1002] title];
            [webView release];
        }
}

#pragma mark ScrollView Delegate Method
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    if (self.scroll.contentOffset.x == (self.banner.count + 2 - 1) * WIDTH) {
        self.scroll.contentOffset = CGPointMake(WIDTH, 0);
    }
    if (self.scroll.contentOffset.x == 0) {
        self.scroll.contentOffset = CGPointMake((self.banner.count) * WIDTH, 0);
    }
}



#pragma mark CollectionView Setting
- (void)createCollectionView
{
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.itemSize = CGSizeMake(100, 100);
    flowLayout.minimumInteritemSpacing = 1;
    /*! 滑动方向 */
    flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    flowLayout.sectionInset = UIEdgeInsetsMake(1, 3, 1, 3);
    
    
    self.collection = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 215, WIDTH, 115) collectionViewLayout:flowLayout];
    self.collection.backgroundColor = [UIColor whiteColor];
    [self.backOfSCView addSubview:self.collection];
    [flowLayout release];
    [_collection release];
    
    self.collection.layer.borderWidth = 1;
    self.collection.layer.borderColor = [[UIColor whiteColor] CGColor];
    self.collection.showsHorizontalScrollIndicator = NO;
    
    self.collection.delegate = self;
    self.collection.dataSource = self;
    
    
    [self.collection registerClass:[HZMEntry_listCollectionViewCell class] forCellWithReuseIdentifier:@"collectionReuse"];
    
    
}

#pragma mark CollectionView Delegate Method
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.entry_list.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    HZMEntry_listCollectionViewCell *cell = [self.collection dequeueReusableCellWithReuseIdentifier:@"collectionReuse" forIndexPath:indexPath];
    [cell.picImageView sd_setImageWithURL:[NSURL URLWithString:[self.entry_list[indexPath.row] pic1]] placeholderImage:[UIImage imageNamed:@"back.gif"]];
    cell.contentView.backgroundColor = [UIColor cyanColor];

    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        HZMSubject_DetailsViewController *sdVC = [[HZMSubject_DetailsViewController alloc] init];
        sdVC.hidesBottomBarWhenPushed = YES;
        sdVC.list = self.entry_list[indexPath.row];
        [self.navigationController pushViewController:sdVC animated:YES];
        [sdVC release];
    } else {
        HZMOtherViewController *otVC = [[HZMOtherViewController alloc] init];   
        otVC.hidesBottomBarWhenPushed = YES;
        otVC.typeId = [self.entry_list[indexPath.row] collectionId];
        [self.navigationController pushViewController:otVC animated:YES];
        [otVC release];
    }
}



#pragma mark CreateData
- (void)createData
{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    NSString *strUrl = [NSString stringWithFormat:@"http://open3.bantangapp.com/recommend/index?app_installtime=1445332782.662591&app_versions=4.2.2&channel_name=appStore&client_id=bt_app_ios&client_secret=9c1e6634ce1c5098e056628cd66a17a5&oauth_token=bf8be334eb1fd06b1bf65f5883dd415a&os_versions=9.0.2&page=%ld&pagesize=20&screensize=1242&track_device_info=iPhone7%dC1&track_deviceid=2F83AC09-B470-4C43-9DEE-E0FB95B4B438&track_user_id=1457891&v=7", self.page, 2];
    [manager GET:strUrl parameters:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
        
    if (self.page == 0) {
        
        NSMutableDictionary *dic = responseObject;
        self.banner = [NSMutableArray array];
        self.banner = [HZMHomePageBanner baseModelByArr:dic[@"data"][@"banner"]];
        self.entry_list = [NSMutableArray array];
        self.entry_list = [HZMHomePageEntry_list baseModelByArr:dic[@"data"][@"entry_list"]];
        self.topic = [NSMutableArray array];
        self.topic = [HZMHomePageTopic baseModelByArr:dic[@"data"][@"topic"]];
        
        if (self.topic.count > 0) {
            
            [self.tableView reloadData];
            [self reloadScrollViewData];
            [self.collection reloadData];
            [self.hud removeFromSuperview];
            [self.tableView.header endRefreshing];
        }
        
    } else {
        NSMutableDictionary *dic = responseObject;
        NSMutableArray *arr = [NSMutableArray array];
        arr = [HZMHomePageTopic baseModelByArr:dic[@"data"][@"topic"]];
        [self.topic addObjectsFromArray:arr];
        [self.tableView reloadData];
        [self.tableView.footer endRefreshing];
        if (self.page >= 21) {
            [self.tableView.footer endRefreshingWithNoMoreData];
        }
    }
    } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
        NSLog(@"%@", error);
        
    }];
}

- (void) createNetWork {
    AFNetworkReachabilityManager *manager =  [AFNetworkReachabilityManager sharedManager];
//    [AFNetworkReachabilityManager sharedManager];
    [manager startMonitoring];
    [manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        
        [self showNetWorkWithStatus:status];
        
    }];
}

- (void) showNetWorkWithStatus:(NSInteger)status {
    NSString *str;
    switch (status) {
        case AFNetworkReachabilityStatusUnknown:
            str = @"未知网络";
            [self.hud removeFromSuperview];
            break;
        case AFNetworkReachabilityStatusNotReachable:
            str = @"网络未连接";
            
            [self.hud removeFromSuperview];
            break;
        case AFNetworkReachabilityStatusReachableViaWWAN:
            str = @"网络已连接";
            [self createData];
            break;
        case AFNetworkReachabilityStatusReachableViaWiFi:
            str = @"wifi已连接";
            [self createData];
            break;
        default:
            break;
    }
    if (![str isEqualToString:@"wifi已连接"] || [str isEqualToString:@"网络已连接"]) {
        
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"当前网络状态" message:str preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:nil];
        [alert addAction:cancel];
        [self presentViewController:alert animated:YES completion:nil];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
